{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-20T09:35:56.628130Z",
     "start_time": "2019-03-20T09:35:45.661384Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Administrator\\Anaconda3\\lib\\requests\\__init__.py:80: RequestsDependencyWarning: urllib3 (1.25.11) or chardet (3.0.4) doesn't match a supported version!\n",
      "  RequestsDependencyWarning)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "matchzoo version 1.0.2\n",
      "`ranking_task` initialized with metrics [normalized_discounted_cumulative_gain@3(0.0), normalized_discounted_cumulative_gain@5(0.0), mean_average_precision(0.0)]\n",
      "data loading ...\n",
      "data loaded as `train_pack_raw` `dev_pack_raw` `test_pack_raw`\n",
      "停用表配置成功\n"
     ]
    }
   ],
   "source": [
    "%run init.ipynb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-20T09:35:56.633000Z",
     "start_time": "2019-03-20T09:35:56.630450Z"
    },
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "preprocessor = mz.preprocessors.BasicPreprocessor(\n",
    "    truncated_length_left = 10,\n",
    "    truncated_length_right = 100,\n",
    "    filter_low_freq = 1\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-20T09:36:06.249211Z",
     "start_time": "2019-03-20T09:35:56.634788Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval:   0%| | 0/97 [00:00<?, ?it/s]Building prefix dict from the default dictionary ...\n",
      "Loading model from cache C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\jieba.cache\n",
      "Loading model cost 2.684 seconds.\n",
      "Prefix dict has been built succesfully.\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 97/97 [00:03<00:00, 24.34it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 97/97 [00:01<00:00, 88.88it/s] \n",
      "Processing text_right with append: 100%|████████████████████████████████████████████| 97/97 [00:00<00:00, 48526.66it/s]\n",
      "Building FrequencyFilter from a datapack.: 100%|████████████████████████████████████| 97/97 [00:00<00:00, 32356.25it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 97/97 [00:00<00:00, 48544.03it/s]\n",
      "Processing text_left with extend: 100%|█████████████████████████████████████████████| 97/97 [00:00<00:00, 48526.66it/s]\n",
      "Processing text_right with extend: 100%|████████████████████████████████████████████| 97/97 [00:00<00:00, 32361.40it/s]\n",
      "Building Vocabulary from a datapack.: 100%|██████████████████████████████████████| 984/984 [00:00<00:00, 491625.39it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 97/97 [00:00<00:00, 127.87it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 97/97 [00:00<00:00, 130.98it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 97/97 [00:00<00:00, 48567.21it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 97/97 [00:00<00:00, 24279.26it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 97/97 [00:00<00:00, 24266.22it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 97/97 [00:00<00:00, 97053.31it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 97/97 [00:00<00:00, 48555.61it/s]\n",
      "Processing length_left with len: 100%|██████████████████████████████████████████████| 97/97 [00:00<00:00, 10783.99it/s]\n",
      "Processing length_right with len: 100%|█████████████████████████████████████████████| 97/97 [00:00<00:00, 96822.34it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 48/48 [00:00<00:00, 146.87it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 47/47 [00:00<00:00, 93.49it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 47/47 [00:00<00:00, 23512.92it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 48/48 [00:00<00:00, 24010.33it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 47/47 [00:00<00:00, 23563.51it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 48/48 [00:00<00:00, 24151.46it/s]\n",
      "Processing text_right with transform: 100%|██████████████████████████████████████████| 47/47 [00:00<00:00, 7837.95it/s]\n",
      "Processing length_left with len: 100%|██████████████████████████████████████████████| 48/48 [00:00<00:00, 48083.73it/s]\n",
      "Processing length_right with len: 100%|██████████████████████████████████████████████| 47/47 [00:00<00:00, 9361.84it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 29/29 [00:00<00:00, 86.88it/s] \n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 30/30 [00:00<00:00, 73.93it/s] \n",
      "Processing text_right with transform: 100%|██████████████████████████████████████████| 30/30 [00:00<00:00, 7497.86it/s]\n",
      "Processing text_left with transform: 100%|███████████████████████████████████████████| 29/29 [00:00<00:00, 4832.92it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 30/30 [00:00<00:00, 14992.15it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 29/29 [00:00<00:00, 14565.30it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 30/30 [00:00<00:00, 30002.17it/s]\n",
      "Processing length_left with len: 100%|██████████████████████████████████████████████| 29/29 [00:00<00:00, 29022.86it/s]\n",
      "Processing length_right with len: 100%|█████████████████████████████████████████████| 30/30 [00:00<00:00, 14985.01it/s]\n"
     ]
    }
   ],
   "source": [
    "train_pack_processed = preprocessor.fit_transform(train_pack_raw)\n",
    "dev_pack_processed = preprocessor.transform(dev_pack_raw)\n",
    "test_pack_processed = preprocessor.transform(test_pack_raw)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-20T09:36:06.262937Z",
     "start_time": "2019-03-20T09:36:06.253350Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'embedding_input_dim': 357,\n",
       " 'filter_unit': <mzcn.preprocessors.units.frequency_filter.FrequencyFilter at 0x2ca311fec18>,\n",
       " 'vocab_size': 357,\n",
       " 'vocab_unit': <mzcn.preprocessors.units.vocabulary.Vocabulary at 0x2ca3ac77be0>}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "preprocessor.context"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# glove_embedding = mz.datasets.embeddings.load_glove_embedding(dimension=100)\n",
    "# term_index = preprocessor.context['vocab_unit'].state['term_index']\n",
    "# embedding_matrix = glove_embedding.build_matrix(term_index)\n",
    "# l2_norm = np.sqrt((embedding_matrix * embedding_matrix).sum(axis=1))\n",
    "# embedding_matrix = embedding_matrix / l2_norm[:, np.newaxis]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "trainset = mz.dataloader.Dataset(\n",
    "    data_pack=train_pack_processed,\n",
    "    mode='pair',\n",
    "    num_dup=2,\n",
    "    num_neg=1\n",
    ")\n",
    "devset = mz.dataloader.Dataset(\n",
    "    data_pack=dev_pack_processed\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "padding_callback = mz.models.DRMMTKS.get_default_padding_callback()\n",
    "\n",
    "trainloader = mz.dataloader.DataLoader(\n",
    "    dataset=trainset,\n",
    "    stage='train',\n",
    "    callback=padding_callback,\n",
    ")\n",
    "devloader = mz.dataloader.DataLoader(\n",
    "    dataset=devset,\n",
    "    stage='dev',\n",
    "    callback=padding_callback,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-20T09:36:06.413530Z",
     "start_time": "2019-03-20T09:36:06.267256Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "DRMMTKS(\n",
      "  (embedding): Embedding(357, 100, padding_idx=0)\n",
      "  (attention): Attention(\n",
      "    (linear): Linear(in_features=100, out_features=1, bias=False)\n",
      "  )\n",
      "  (mlp): Sequential(\n",
      "    (0): Sequential(\n",
      "      (0): Linear(in_features=10, out_features=128, bias=True)\n",
      "      (1): Tanh()\n",
      "    )\n",
      "    (1): Sequential(\n",
      "      (0): Linear(in_features=128, out_features=128, bias=True)\n",
      "      (1): Tanh()\n",
      "    )\n",
      "    (2): Sequential(\n",
      "      (0): Linear(in_features=128, out_features=128, bias=True)\n",
      "      (1): Tanh()\n",
      "    )\n",
      "    (3): Sequential(\n",
      "      (0): Linear(in_features=128, out_features=1, bias=True)\n",
      "      (1): Tanh()\n",
      "    )\n",
      "  )\n",
      "  (out): Linear(in_features=1, out_features=1, bias=True)\n",
      ")\n",
      "Trainable params:  70363\n"
     ]
    }
   ],
   "source": [
    "model = mz.models.DRMMTKS()\n",
    "\n",
    "model.params['task'] = ranking_task\n",
    "# model.params['embedding'] = embedding_matrix #这里是当加载glove等模型时取消该行注释\n",
    "#设置embedding系数\n",
    "model.params[\"embedding_output_dim\"]=100\n",
    "model.params[\"embedding_input_dim\"]=preprocessor.context[\"embedding_input_dim\"]\n",
    "model.params['mask_value'] = 0\n",
    "model.params['top_k'] = 10\n",
    "model.params['mlp_activation_func'] = 'tanh'\n",
    "\n",
    "model.build()\n",
    "\n",
    "print(model)\n",
    "print('Trainable params: ', sum(p.numel() for p in model.parameters() if p.requires_grad))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-20T09:36:06.422264Z",
     "start_time": "2019-03-20T09:36:06.415605Z"
    },
    "collapsed": true,
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "optimizer = torch.optim.Adadelta(model.parameters())\n",
    "\n",
    "trainer = mz.trainers.Trainer(\n",
    "    model=model,\n",
    "    optimizer=optimizer,\n",
    "    trainloader=trainloader,\n",
    "    validloader=devloader,\n",
    "    validate_interval=None,\n",
    "    epochs=10\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-20T09:37:59.341616Z",
     "start_time": "2019-03-20T09:36:06.425086Z"
    }
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "111307fd02714af5b636cb97a231d76a",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-1 Loss-1.000]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.4062 - normalized_discounted_cumulative_gain@5(0.0): 0.4062 - mean_average_precision(0.0): 0.4062\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "001965988cf047fdb8649ba36f60faf3",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-2 Loss-0.995]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.4062 - normalized_discounted_cumulative_gain@5(0.0): 0.4062 - mean_average_precision(0.0): 0.4062\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "a62806808a1f4b8b9ea9f569a5d28e6b",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-3 Loss-0.988]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.4062 - normalized_discounted_cumulative_gain@5(0.0): 0.4062 - mean_average_precision(0.0): 0.4062\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "f72fd7fa9dc24f208fe978c0dcc00dba",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-4 Loss-0.979]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.4062 - normalized_discounted_cumulative_gain@5(0.0): 0.4062 - mean_average_precision(0.0): 0.4062\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "fc48353ff16344828bcc893616954bd0",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-5 Loss-0.963]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.4062 - normalized_discounted_cumulative_gain@5(0.0): 0.4062 - mean_average_precision(0.0): 0.4062\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "31ab375d26ff46a8aff7b52fddac3b17",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-6 Loss-0.934]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.4062 - normalized_discounted_cumulative_gain@5(0.0): 0.4062 - mean_average_precision(0.0): 0.4062\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "dd7284267d154556a62ab50cbd155127",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-7 Loss-0.877]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.4062 - normalized_discounted_cumulative_gain@5(0.0): 0.4062 - mean_average_precision(0.0): 0.4062\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "4a69b3f767744763924a324108b64d32",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-8 Loss-0.772]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.4062 - normalized_discounted_cumulative_gain@5(0.0): 0.4062 - mean_average_precision(0.0): 0.4062\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "c17ea9793c2947cbb54eae265ce45828",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-9 Loss-0.616]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.4062 - normalized_discounted_cumulative_gain@5(0.0): 0.4062 - mean_average_precision(0.0): 0.4062\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "11c2c49dd59e4004b122b62e373d1a5b",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-10 Loss-0.469]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.4062 - normalized_discounted_cumulative_gain@5(0.0): 0.4062 - mean_average_precision(0.0): 0.4062\n",
      "\n",
      "Cost time: 4.3155272006988525s\n"
     ]
    }
   ],
   "source": [
    "trainer.run()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import gc\n",
    "gc.collect()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "hide_input": false,
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  },
  "toc": {
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": "block",
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
